<?php

// ==============================================================================
//
// This file is part of the WelSpeak.
//
// Create by Welfony Support <support@welfony.com>
// Copyright (c) 2012-2014 welfony.com
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//
// ==============================================================================

use Flysystem\Filesystem;
use Flysystem\Adapter\Local as FilesystemAdapter;
use PrettyDateTime\PrettyDateTime;
use Welfony\Welspeak\Core\Enum\MessageStatus;
use Welfony\Welspeak\Repository\MessageRepository;
use Welfony\Welspeak\Utility\Util;

$app->post('/feedback', function() use($app) {

});

$app->get('/messages/sender/:senderId/receiver/:receiverId', function($senderId, $receiverId) use($app) {
    $page = intval($app->request->get('page'));
    $page = $page <= 0 ? 1 : $page;
    $pageSize = intval($app->request->get('pageSize'));
    $pageSize = $pageSize <= 0 ? 20 : $pageSize;

    $totalResultsCount = MessageRepository::getAllMessagesCountByReceiverAndSender($senderId, $receiverId);
    $totalResults = array();
    $messages = MessageRepository::getAllMessagesByReceiverAndSender($senderId, $receiverId, $page, $pageSize);
    foreach ($messages as $msg) {
        $msg['CreatedDate'] = PrettyDateTime::parse(new DateTime($msg['CreatedDate']));
        $totalResults[] = $msg;
    }

    MessageRepository::updateStatusByReceiver($senderId, MessageStatus::Read);

    sendResponse(array('total' => $totalResultsCount, 'messages' => $totalResults));
})->conditions(array('senderId' => '\d{1,10}', 'receiverId' => '\d{1,10}'));

$app->post('/messages', function() use($app) {
    $reqData = getDataFromRequestWithJsonFormat();

    if (!isset($reqData['senderId']) || intval($reqData['senderId']) <= 0) {
        sendInvalidFieldResult('Message', 'senderId', 'missing_field');
    }
    if (!isset($reqData['receiverId']) || intval($reqData['receiverId']) <= 0) {
        sendInvalidFieldResult('Message', 'receiverId', 'missing_field');
    }
    if (!isset($reqData['media']) || empty($reqData['media'])) {
        sendInvalidFieldResult('Message', 'media', 'missing_field');
    }
    $senderId = intval($reqData['senderId']);
    $receiverId = intval($reqData['receiverId']);
    $media = $reqData['media'];

    $hashFileName = base64_encode(date('Ymdhis') . uniqid());
    $ext = '.caf';

    $filemanager = new Filesystem(new FilesystemAdapter($app->config['app']['media_path']));
    $filemanager->createDir(implode(DS, array(date('Y'), date('m'), date('d'))));

    $fileTargetRelatedPath = implode(DS, array(date('Y'), date('m'), date('d'), $hashFileName . $ext));
    $fileTargetPath = implode(DS, array($app->config['app']['media_path'], $fileTargetRelatedPath));

    file_put_contents($fileTargetPath, base64_decode($media));

    $message = array(
        'SenderId' => $senderId,
        'ReceiverId' => $receiverId,
        'MediaUrl' => $app->config['app']['asset_base_url'] . '/media/' . implode('/', array(date('Y'), date('m'), date('d'), $hashFileName . $ext)),
        'MediaLength' => 10,
        'Status' => MessageStatus::Unread,
        'CreatedDate' => date('Y-m-d H:i:s')
    );

    $newMessageId = MessageRepository::save($message);
    if ($newMessageId) {
        $message['MessageId'] = $newMessageId;
        sendResponse($message);
    } else {
        sendOperationFailedResult('Message');
    }
});

$app->get('/messages/remove/:messageId', function($messageId) use($app) {
    sendResponse(array('success' => MessageRepository::remove($messageId)));
})->conditions(array('messageId' => '\d{1,10}'));